package com.supply.controller;

import com.supply.pojo.Permission;
import com.supply.pojo.ResultBean;
import com.supply.pojo.User;
import com.supply.service.PermissionService;
import com.supply.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public ResultBean login(HttpServletRequest request){
        //获取登录认证器所记录的登录错误信息
        String errorMsg = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);

        //若错误信息不为空，则判断错误类型是属于密码错误还是账号错误，并返回
        if(errorMsg != null) {
            if(errorMsg.equals(UnknownAccountException.class.getName()) ||
                    errorMsg.equals(IncorrectCredentialsException.class.getName())) {
                return ResultBean.error("用户名或密码错误");
            }
        }
        return ResultBean.info("请登录");
    }

    //自定义的认证过滤器所设置的登录成功跳转的接口，用于返回登录的用户信息，并保存到session
    @GetMapping("/toLoginSuccess")
    public ResultBean toLoginSuccess(HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        System.out.println("登录成功的用户：" + user);
        session.setAttribute("loginUser",user);
        return ResultBean.success(user);
    }

    //权限匹配失败所跳转的接口
    @GetMapping("/noPermission")
    public ResultBean noPermission(){
        return ResultBean.noPermission();
    }



    @GetMapping("/connectTest")
    public ResultBean connectTest(){
        return ResultBean.success();
    }


}
